package com.cn.medicalcare.customtool;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.util.function.Function;

public class SqlSessionFactoryTool {
    private static final String resource = "mybatis-config/configuration.xml";
    private static SqlSessionFactory sqlSessionFactory;

    static {
        try {
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream(resource));
        } catch (IOException e) {
        }
    }

    public static <T, R> T DoMapper(Class<R> clazz, Function<R, T> work) {
        SqlSession sqlSession = null;
        T t = null;
        try {
            sqlSession = sqlSessionFactory.openSession();
            R r = sqlSession.getMapper(clazz);
            t = work.apply(r);
        } catch (Exception e) {
        } finally {
            if (sqlSession != null)
                sqlSession.close();
        }
        return t;
    }

    public static <T, R> T DoMapperAndCommit(Class<R> clazz, Function<R, T> work) {
        SqlSession sqlSession = null;
        T t = null;
        try {
            sqlSession = sqlSessionFactory.openSession();
            R r = sqlSession.getMapper(clazz);
            t = work.apply(r);
            sqlSession.commit();
        } catch (Exception e) {
            if (sqlSession != null)
                sqlSession.rollback();
        } finally {
            if (sqlSession != null)
                sqlSession.close();
        }
        return t;
    }
}
